package com.kly.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.kly.common.ErrorCode;
import com.kly.common.Result;
import com.kly.common.UserContext;
import com.kly.exception.BusinessException;
import com.kly.model.domain.User;
import com.kly.model.dto.PageQuery;
import com.kly.model.dto.UserLoginDto;
import com.kly.model.dto.UserRegisterDto;
import com.kly.model.vo.PageResult;
import com.kly.model.vo.UserVo;
import com.kly.service.UserService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

import static com.kly.constant.UserConstant.LOGIN_USER_KEY;

/**
 * @author admin
 * @date 2025/2/16
 */
@RequestMapping("/user")
@RestController
@RequiredArgsConstructor
// @CrossOrigin(origins = {"http://localhost:5173"}, allowedHeaders = "true")
public class UserController {

    private final UserService userService;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;


    /**
     * 用户注册
     */
    @PostMapping("/register")
    public Result<Long> userRegister(@RequestBody UserRegisterDto userRegisterDto) {
        if (userRegisterDto == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        //     获取用户信息
        String account = userRegisterDto.getAccount();
        String password = userRegisterDto.getPassword();
        String checkPassword = userRegisterDto.getCheckPassword();
        String planetCode = userRegisterDto.getPlanetCode();
        //     验证非空
        if (StringUtils.isAnyBlank(account, password, checkPassword, planetCode)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        long count = userService.userRegister(account, password, checkPassword, planetCode);
        return Result.success(count);
    }

    /**
     * 用户登录
     */
    @PostMapping("/login")
    public Result<UserVo> userLogin(@RequestBody UserLoginDto userLoginDto) {
        if (userLoginDto == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        //     获取用户信息
        String account = userLoginDto.getAccount();
        String password = userLoginDto.getPassword();
        //     验证非空
        if (StringUtils.isAnyBlank(account, password)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        return Result.success(userService.userLogin(account, password));
    }

    /**
     * 用户退出
     */
    @PostMapping("/logout")
    public Result<String> userLogout() {
        // 清除缓存
        redisTemplate.delete(LOGIN_USER_KEY);
        UserContext.removeUser();

        return Result.success("ok");
    }

    /**
     * 用户查询
     */
    @GetMapping("/search")
    public Result<List<User>> searchUsers(String username) {
        if (!userService.isAdmin()) {
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
        //     返回结果
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<User>()
                .like(StringUtils.isNotBlank(username), User::getUsername, username);
        List<User> userList = userService.list(queryWrapper);
        // 用户脱敏
        List<User> users = userList.stream().map(userService::getSafetyUser).collect(Collectors.toList());
        return Result.success(users);
    }


    /**
     * 查询当前用户
     */
    @GetMapping("/current")
    public Result<User> currentUser() {
        User user = userService.getById(UserContext.getUser().getId());
        User safetyUser = userService.getSafetyUser(user);
        UserContext.setUser(safetyUser);
        return Result.success(safetyUser);
    }

    /**
     * 删除用户
     */
    @PostMapping("/delete")
    public Result<Boolean> deleteUser(@RequestBody Long id) {
        if (!userService.isAdmin()) {
            throw new BusinessException(ErrorCode.NO_AUTH);
        }

        if (id <= 0) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR);
        }
        return Result.success(userService.removeById(id));
    }


    /**
     * 根据tags搜索用户
     */
    @GetMapping("/search/tags")
    public Result<List<User>> searchByTags(@RequestParam(required = false) List<String> searchTags) {
        if (CollectionUtils.isEmpty(searchTags)) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        List<User> users = userService.searchUserByTags(searchTags);
        return Result.success(users);
    }

    /**
     * 更新用户
     */
    @PostMapping("/update")
    public Result<Integer> update(@RequestBody User user) {
        if (user == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = UserContext.getUser();
        Integer result = userService.updateUser(user, loginUser);
        return Result.success(result);
    }


    /**
     * 推荐用户
     */
    @GetMapping("/recommend")
    // @Cacheable(value = "user_recommend", key = "#pageQuery.pageNo")
    public Result<PageResult<User>> recommendUsers(PageQuery pageQuery) {
        if (pageQuery == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        PageResult<User> userPageResult = userService.recommendUsers(pageQuery);

        return Result.success(userPageResult);
    }

}
